package pubsub

import (
	"gitee.com/liukexing/mqbroker/core/driver/config"
	"sync"

	"gitee.com/liukexing/mqbroker/core/driver/natsio"
	"gitee.com/liukexing/mqbroker/core/driver/nsqio"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"time"
)

const (
	ConfigName = "config.core.server.pubsub"
)

var (
	Config    typedef.ConfigInfo
	Server    typedef.PubSubServer
	drivermap sync.Map
)

func init() {
	var ok bool
	Config, ok = config.GetConfig(ConfigName)
	if !ok {
		return
	}
	drivermap.Store("nsqio_Check", nsqio.CheckModule)
	drivermap.Store("nsqio_New", nsqio.NewPubSubServer)

	drivermap.Store("natsio_Check", natsio.CheckModule)
	drivermap.Store("natsio_New", natsio.NewPubSubServer)
}

func Run() bool {
	Server = NewPubSubServer()
	initCommand()
	initCompute()
	MessageReplyServer(Config.Info, nil)
	return Server == nil
}

//nsqio
type ServerHandler struct {
	typedef.PubSubServer
	handel typedef.PubSubServer
}

func NewPubSubServer() typedef.PubSubServer {
	driver := Config.Extend["driver"].(string)
	if mqio, ok := drivermap.Load(driver + "_Check"); !ok || !mqio.(func() bool)() {
		return nil
	}
	if mqio, ok := drivermap.Load(driver + "_New"); !ok {
		return nil
	} else {
		return &ServerHandler{
			handel: mqio.(func() typedef.PubSubServer)(),
		}
	}

}

func (h *ServerHandler) GetPubConfig() interface{} {
	return h.handel.GetPubConfig()
}

func (h *ServerHandler) GetSubConfig() interface{} {
	return h.handel.GetSubConfig()
}

func (h *ServerHandler) NewPublisher(name string, config interface{}, topic string) bool {
	return h.handel.NewPublisher(name, config, topic)
}

func (h *ServerHandler) Publish(name string, message string) bool {
	return h.handel.Publish(name, message)
}

func (h *ServerHandler) DeferredPublish(name string, message string, delay time.Duration) bool {
	return h.handel.DeferredPublish(name, message, delay)
}

func (h *ServerHandler) DelPublisher(name string) bool {
	return h.handel.DelPublisher(name)
}

func (h *ServerHandler) NewSubscriber(name string, config interface{}, topic string) bool {
	return h.handel.NewSubscriber(name, config, topic)
}
func (h *ServerHandler) AddSubscriber(channel string, name string, handel typedef.MessageHandle) bool {
	return h.handel.AddSubscriber(channel, name, handel)
}
func (h *ServerHandler) RemoveSubscriber(channel string, name string) bool {
	return h.handel.RemoveSubscriber(channel, name)
}
func (h *ServerHandler) DelSubscriber(name string) bool {
	return h.handel.DelSubscriber(name)
}
func (h *ServerHandler) Request(name string, message interface{}, timeout time.Duration) typedef.ResponseData {
	return h.handel.Request(name, message, timeout)
}
func (h *ServerHandler) AddReply(name string, handel typedef.ReplyHandle) bool {
	return h.handel.AddReply(name, handel)
}
func (h *ServerHandler) RemoveReply(name string) bool {
	return h.handel.RemoveReply(name)
}
